<template>
  <div class="home-page">
    <!-- 欢迎信息 -->
    <div class="welcome-section">
      <h2>欢迎使用签证管理系统</h2>
      <p>{{ currentTime }}</p>
    </div>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="data-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-icon" style="background-color: #409EFF">
              <i class="el-icon-s-order"></i>
            </div>
            <div class="data-info">
              <div class="data-title">总订单数</div>
              <div class="data-value">2,356</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-icon" style="background-color: #67C23A">
              <i class="el-icon-user"></i>
            </div>
            <div class="data-info">
              <div class="data-title">客户总数</div>
              <div class="data-value">1,823</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-icon" style="background-color: #E6A23C">
              <i class="el-icon-money"></i>
            </div>
            <div class="data-info">
              <div class="data-title">本月营收</div>
              <div class="data-value">￥286,392</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="data-item">
            <div class="data-icon" style="background-color: #F56C6C">
              <i class="el-icon-s-data"></i>
            </div>
            <div class="data-info">
              <div class="data-title">商品总数</div>
              <div class="data-value">18</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 便签区域 -->
    <el-row :gutter="20" class="notes-section">
      <el-col :span="24">
        <el-card class="notes-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>我的便签</span>
            <el-button type="text" icon="el-icon-plus" @click="showAddNoteDialog">新增便签</el-button>
          </div>
          <div class="notes-list">
            <transition-group name="note-item" tag="div" class="notes-container">
              <el-card 
                v-for="(note, index) in notes" 
                :key="note.id"
                class="note-item" 
                shadow="hover"
              >
                <div class="note-content">
                  <el-input
                    type="textarea"
                    v-model="note.content"
                    :rows="3"
                    placeholder="请输入便签内容"
                  />
                </div>
                <div class="note-footer">
                  <span class="note-time">{{ note.time }}</span>
                  <div class="note-actions">
                    <el-button 
                      type="text" 
                      icon="el-icon-check"
                      @click="saveNote(index)"
                    >
                      确定
                    </el-button>
                    <el-button 
                      type="text" 
                      icon="el-icon-delete" 
                      @click="deleteNote(index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </el-card>
            </transition-group>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增便签弹窗 -->
    <el-dialog title="新增便签" :visible.sync="noteDialogVisible" width="400px">
      <el-input
        type="textarea"
        v-model="newNoteContent"
        :rows="4"
        placeholder="请输入便签内容"
        maxlength="500"
        show-word-limit
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="noteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddNote">确 定</el-button>
      </span>
    </el-dialog>

        <!-- 材料邮寄地址管理 -->
        <el-row :gutter="20" class="address-section">
      <el-col :span="24">
        <el-card class="address-card" shadow="hover">
          <div slot="header" class="card-header address-header">
            <span>材料邮寄地址</span>
            <div class="address-header-btn">
              <el-button class="address-add-btn" icon="el-icon-plus" size="mini" @click="showAddressDialog = true; addressForm = {name: '', phone: '', address: '', status: 1, id: null}; isEditAddress = false;">新增地址</el-button>
            </div>
          </div>
          <el-table :data="addressList" style="width: 100%; margin-bottom: 20px;" border>
            <el-table-column prop="name" label="姓名" width="120"/>
            <el-table-column prop="phone" label="手机号" width="150"/>
            <el-table-column prop="address" label="邮寄地址"/>
            <el-table-column prop="status" label="显示状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '显示' : '隐藏' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="left">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="editAddress(scope.row)">编辑</el-button>
                <el-button type="text" size="mini" style="color: #F56C6C" @click="deleteAddress(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 地址编辑对话框 -->
          <el-dialog :title="isEditAddress ? '编辑地址' : '新增地址'" :visible.sync="showAddressDialog" width="400px">
            <el-form :model="addressForm" label-width="80px" :rules="addressRules" ref="addressForm">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="addressForm.name" maxlength="20"/>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="addressForm.phone" maxlength="20"/>
              </el-form-item>
              <el-form-item label="邮寄地址" prop="address">
                <el-input v-model="addressForm.address" maxlength="100"/>
              </el-form-item>
              <el-form-item label="显示状态" prop="status">
                <el-switch v-model="addressForm.status" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="隐藏"/>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="showAddressDialog = false">取消</el-button>
              <el-button type="primary" @click="submitAddress">确定</el-button>
            </span>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="proposal-section">
      <el-col :span="24">
        <el-card class="proposal-card" shadow="hover">
          <div slot="header" class="card-header">
            <span>用户建议</span>
            <el-button type="text" icon="el-icon-refresh" @click="fetchProposals">刷新</el-button>
          </div>
          
          <!-- 添加搜索区域 -->
          <div class="search-container">
            <el-select v-model="searchType" placeholder="选择搜索类型" style="width: 120px; margin-right: 10px">
              <el-option label="昵称" value="nickName"/>
              <el-option label="手机号" value="phoneNumber"/>
              <el-option label="反馈类型" value="proposalType"/>
            </el-select>
            <el-input
              v-model="searchKeyword"
              :placeholder="`请输入${getPlaceholder}`"
              clearable
              @clear="handleSearch"
              style="width: 300px">
              <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-input>
          </div>
          <!-- 表格部分修改 -->
          <el-table :data="filteredProposals.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
                    style="width: 100%; margin-top: 15px">
            <el-table-column prop="nickName" label="用户昵称" width="120"/>
            <el-table-column prop="phoneNumber" label="联系电话" width="120"/>
            <el-table-column prop="proposalType" label="反馈类型" width="120"/>
            <el-table-column prop="content" label="建议内容"/>
            <el-table-column prop="createTime" label="提交时间" width="180">
              <template slot-scope="scope">
                {{ new Date(scope.row.createTime).toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="handleDeleteProposal(scope.row)" class="delete-btn">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 添加分页组件 -->
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="filteredProposals.length">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>

import axios from '@/utils/request'
export default {
  name: "HomePage",
  data() {
    return {
      noteDialogVisible: false,
      newNoteContent: '',
      currentTime: '',
      currentPage: 1,  // 当前页码
      pageSize: 10,    // 每页显示条数
      proposals: [],
      searchType: 'nickName',  
      searchKeyword: '',
      notes: [],
      addressList: [],
      addressForm: { name: '', phone: '', address: '', status: 1, id: null },
      showAddressDialog: false,
      isEditAddress: false,
      addressRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入邮寄地址', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 动态获取输入框的 placeholder
    getPlaceholder() {
      const placeholderMap = {
        nickName: '用户昵称',
        phoneNumber: '手机号',
        proposalType: '反馈类型'
      }
      return placeholderMap[this.searchType]
    },
    filteredProposals() {
      if (!this.searchKeyword) return this.proposals;
      return this.proposals.filter(item => {
        const keyword = this.searchKeyword.toLowerCase();
        const value = item[this.searchType].toLowerCase();
        return value.includes(keyword);
      });
    }
  },
  mounted() {
    this.updateTime()
    setInterval(this.updateTime, 1000)
    this.fetchProposals()
    this.fetchAddressList()
    this.fetchNotes()
  },
  methods: {
    // 便签管理相关
    async fetchNotes() {
      try {
        console.debug('[便签] GET /admin/visa/note 请求')
        const res = await axios.get('/admin/visa/note')
        console.debug('[便签] GET 响应:', res)
        if (Array.isArray(res)) {
          this.notes = res
        } else if (res && res.data) {
          this.notes = res.data
        } else {
          this.notes = []
        }
      } catch (e) {
        console.error('[便签] 获取失败:', e)
        this.$message.error('获取便签失败')
      }
    },
    showAddNoteDialog() {
      this.newNoteContent = ''
      this.noteDialogVisible = true
    },
    async confirmAddNote() {
      if (!this.newNoteContent.trim()) {
        this.$message.warning('请输入便签内容')
        return
      }
      try {
        const newNote = { content: this.newNoteContent }
        console.debug('[便签] POST /admin/visa/note 请求:', newNote)
        const res = await axios.post('/admin/visa/note', newNote)
        console.debug('[便签] POST 响应:', res)
        let noteObj = (res && res.data) ? res.data : res;
        if (noteObj && noteObj.id) {
          this.notes.unshift(noteObj)
        } else {
          await this.fetchNotes();
        }
        this.$message.success('新增便签成功')
        this.noteDialogVisible = false
      } catch (e) {
        console.error('[便签] 新增失败:', e)
        this.$message.error('新增便签失败')
      }
    },
    async saveNote(index) {
      const note = this.notes[index]
      const updateData = { id: note.id, content: note.content }
      try {
        console.debug('[便签] PUT /admin/visa/note 请求:', updateData)
        const res = await axios.put('/admin/visa/note', updateData)
        console.debug('[便签] PUT 响应:', res)
        this.$message.success('保存成功')
        this.fetchNotes()
      } catch (e) {
        console.error('[便签] 保存失败:', e)
        this.$message.error('保存失败')
      }
    },
    async deleteNote(index) {
      const note = this.notes[index]
      try {
        await this.$confirm('是否删除该便签的一切？删除后无法恢复。', '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        console.debug('[便签] DELETE /admin/visa/note/' + note.id)
        const res = await axios.delete(`/admin/visa/note/${note.id}`)
        console.debug('[便签] DELETE 响应:', res)
        let deletedId = (res && res.data) ? res.data : null;
        if (deletedId) {
          this.notes = this.notes.filter(n => n.id !== deletedId)
        } else {
          await this.fetchNotes();
        }
        this.$message.success('删除成功')
      } catch (e) {
        if (e !== 'cancel') {
          console.error('[便签] 删除失败:', e)
          this.$message.error('删除失败')
        }
      }
    },
    // 地址管理相关
    async fetchAddressList() {
      try {
        const res = await axios.get('/admin/user/address')
        if (Array.isArray(res)) {
          this.addressList = res
        } else if (res && res.data) {
          this.addressList = res.data
        } else {
          this.addressList = []
        }
      } catch (e) {
        this.$message.error('获取地址列表失败')
      }
    },
    submitAddress() {
      this.$refs.addressForm.validate(async valid => {
        if (!valid) return
        try {
          if (this.isEditAddress && this.addressForm.id) {
            await axios.put('/admin/user/address', this.addressForm)
            this.$message.success('修改成功')
          } else {
            await axios.post('/admin/user/address', this.addressForm)
            this.$message.success('添加成功')
          }
          this.showAddressDialog = false
          this.fetchAddressList()
        } catch (e) {
          this.$message.error('保存失败')
        }
      })
    },
    editAddress(row) {
      this.addressForm = Object.assign({}, row)
      this.isEditAddress = true
      this.showAddressDialog = true
    },
    async deleteAddress(id) {
      try {
        await this.$confirm('确认删除该地址？', '提示', { type: 'warning' })
        await axios.delete(`/admin/user/address/${id}`)
        this.$message.success('删除成功')
        this.fetchAddressList()
      } catch (e) {
        if (e !== 'cancel') this.$message.error('删除失败')
      }
    },
    updateTime() {
      this.currentTime = new Date().toLocaleString()
    },

    
    handleSearch() {
      this.currentPage = 1; // 搜索时重置到第一页
    },

    
    async fetchProposals() {
          try {
            // 修改请求路径，添加 /api 前缀
            const res = await axios.get('/admin/user/proposal/list')
            if (res.code === 1) {
              this.proposals = res.data
            } else {
              this.$message.error(res.msg || '获取建议列表失败')
            }
          } catch (error) {
            console.error('获取建议列表失败：', error)
            this.$message.error('获取建议列表失败')
          }
        },

        async handleDeleteProposal(row) {
          try {
            await this.$confirm('确认删除该条建议?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })

            // 修复模板字符串语法和请求路径
            const res = await axios.delete(`/admin/user/proposal/${row.id}`)
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.fetchProposals()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            if (error !== 'cancel') {
              console.error('删除建议失败：', error)
              this.$message.error('删除失败')
            }
          }
        },
    
    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1  // 重置到第一页
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val
    },
    
  }
}
</script>

<style scoped>
.home-page {
  padding: 20px;
}

.welcome-section {
  margin-bottom: 30px;
  text-align: center;
}

.welcome-section h2 {
  color: #303133;
  margin-bottom: 10px;
}

.data-cards {
  margin-bottom: 30px;
}

.data-item {
  display: flex;
  align-items: center;
}

.data-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.data-icon i {
  font-size: 30px;
  color: #fff;
}

.data-info .data-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.data-info .data-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.quick-actions {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.notice-list {
  .notice-item {
    padding: 10px 0;
    border-bottom: 1px solid #EBEEF5;
    display: flex;
    align-items: center;
    
    i {
      color: #E6A23C;
      margin-right: 10px;
    }
    
    &:last-child {
      border-bottom: none;
    }
  }
}

.notes-section {
  margin-bottom: 20px;
}

.notes-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notes-list {
  padding: 10px;
  width: 100%;
}

.notes-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
  width: 100%;
}

.note-item {
  margin: 0;
  height: 100%;
  transition: all 0.3s ease;
}

/* 调整响应式布局断点 */
@media screen and (max-width: 1400px) {
  .note-item {
    flex: 0 0 calc(50% - 8px);
    max-width: calc(50% - 8px);
  }
}

@media screen and (max-width: 900px) {
  .note-item {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

/* 新增便签的动画 */
.note-item-enter-active {
  animation: noteAdd 0.5s ease;
}

.note-item-enter {
  opacity: 0;
  transform: translateX(30px);
}

@keyframes noteAdd {
  0% {
    opacity: 0;
    transform: translateX(30px);
    background-color: #ffd39b;
  }
  50% {
    opacity: 1;
    transform: translateX(0);
    background-color: #ffd39b;
  }
  100% {
    opacity: 1;
    transform: translateX(0);
    background-color: #fff;
  }
}
.note-content {
  margin-bottom: 10px;
}

.note-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.note-time {
  font-size: 12px;
  color: #909399;
}

.proposal-section {
      margin-top: 20px;
    }

    .proposal-card .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .delete-btn {
      color: #F56C6C;
    }
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .search-container {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
  }

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.address-header-btn {
  display: flex;
  align-items: center;
}
.address-section .el-table {
  margin-top: 10px;
}
.address-section .el-table .el-button {
  padding: 0 8px;
}
.address-add-btn {
  background: #fff !important;
  color: #409EFF !important;
  border: none !important;
  box-shadow: none !important;
}
.address-add-btn:hover, .address-add-btn:focus {
  background: #f0f8ff !important;
  color: #1976d2 !important;
  border: none !important;
  box-shadow: none !important;
}

</style>